<script setup>
import {ref, onMounted} from "vue";
import {InfoFilled, Search, Tickets} from "@element-plus/icons-vue";
import {fetchCouponList, deleteCoupon} from "@/api/coupon.js";
import {useRoute,useRouter} from "vue-router";
import {ElMessage} from "element-plus";


const route = useRoute();
const router = useRouter();
const formData = ref({
  name: '',
  type: ''
})
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  name: null,
  type: null
};
const defaultTypeOptions=[
  {
    label: '全场赠券',
    value: 0
  },
  {
    label: '会员赠券',
    value: 1
  },
  {
    label: '购物赠券',
    value: 2
  },
  {
    label: '注册赠券',
    value: 3
  }
];
const listQuery = Object.assign({}, defaultListQuery)
const typeOptions = Object.assign({}, defaultTypeOptions)

onMounted(() => {
  getCouponList();
});
const total = ref(0);
const couponList = ref([]);
const getCouponList = async () => {
  const res = await fetchCouponList(listQuery);
  couponList.value = res.data.data.list;
  total.value = res.data.data.total;
}

// 格式化优惠卷类型
const formatType = (type) => {
  for(let i=0;i<defaultTypeOptions.length;i++){
    if(type===defaultTypeOptions[i].value){
      return defaultTypeOptions[i].label;
    }
  }
  return '未知类型';
}

// 格式化可使用商品
const formatUseType = (useType) => {
  if(useType===0){
    return '全场通用';
  }else if(useType===1){
    return '指定分类';
  }else{
    return '指定商品';
  }
}

// 格式使用平台
const formatPlatform = (platform) => {
  if(platform===1){
    return '移动平台';
  }else if(platform===2){
    return 'PC平台';
  }else{
    return '全平台';
  }
}

// 格式化订单创建时间
const formatDate = (date) => {
  // 检查是否为 Date 对象
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

// 格式化状态
const formatStatus = (endTime) => {
  let now = new Date().getTime();
  let endDate = new Date(endTime);
  if(endDate>now){
    return '未过期'
  }else{
    return '已过期';
  }
}

// 搜索
const handleSearch = () => {
  listQuery.pageNum = 1;
  listQuery.name = formData.value.name;
  listQuery.type = formData.value.type;
  getCouponList();
}

// 重置搜索
const handleResetSearch = () => {
  formData.value = {
    name: '',
    type: ''
  }
  listQuery.name = null;
  listQuery.type = null;
  listQuery.pageNum = 1;
  getCouponList();
}

// TODO: 新增优惠卷
const handleAdd = () => {
  router.push({path: '/detail/coupon/editList'})
}

// TODO: 查看详情
const handleView = (row) => {
  router.push({path: '/detail/coupon/checkList',query:{id:row.id}})
}

// TODO: 编辑优惠卷
const handleUpdate = (row) => {
  router.push({path: '/detail/coupon/editList',query:{id:row.id}})
}

// TODO: 删除优惠卷
const handleDelete = (row) =>{
  deleteCoupon(row.id).then((res) => {
    ElMessage.warning(res.data.message);
    ElMessage.success('删除成功');
  })
  getCouponList();
}


// TODO: 分页操作方法
const handleSizeChange = (size) => {
  listQuery.pageNum = 1;
  listQuery.pageSize = size;
  getCouponList();
}
const handleCurrentChange = (val) => {
  listQuery.pageNum = val;
  getCouponList();
}
</script>

<template>
  <div class="spikes-list">
    <!-- 搜索框 -->
    <div class="spikes-search">
      <div class="logo">
        <div class="logo-text">
          <el-icon>
            <Search/>
          </el-icon>
          <span>筛选搜索</span>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch()">查询结果</el-button>
          <el-button icon="refresh" @click="handleResetSearch()">重置</el-button>
        </div>
      </div>
      <div class="search">
        <el-form :inline="true" ref="searchForm" v-model="formData" label-width="100px">
          <el-form-item label="输入搜索内容:">
            <el-input v-model="formData.name" placeholder="请输入搜索" clearable></el-input>
          </el-form-item>
          <el-form-item label="优惠券类型：">
            <el-select v-model="formData.type" placeholder="全部" clearable class="input-width">
              <el-option v-for="item in typeOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 品牌列表 -->
    <div class="add-list">
      <div class="add-btn">
        <el-icon>
          <Tickets/>
        </el-icon>
        <span>数据列表</span>
      </div>
      <el-button type="primary" icon="plus" style="margin-left: 20px;" @click="handleAdd()">
     优惠卷添加
      </el-button>
    </div>
    <!-- 列表 -->
    <div class="spikes-table">
      <el-table :data="couponList" border style="width: 100%;">
        <el-table-column type="selection" width="100" align="center"></el-table-column>
        <el-table-column label="编号ID" align="center">
          <template #default="{row}">
            {{ row.id }}
          </template>
        </el-table-column>
        <el-table-column label="优惠卷名称" align="center">
          <template #default="{row}">
            {{ row.name }}
          </template>
        </el-table-column>
        <el-table-column label="优惠卷类型" align="center">
          <template #default="{row}">
            {{ formatType(row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="可使用商品" align="center">
          <template #default="{row}">
            {{ formatUseType(row.useType) }}
          </template>
        </el-table-column>
        <el-table-column label="使用门槛" align="center">
          <template #default="{row}">
            满{{ row.minPoint }}
          </template>
        </el-table-column>
        <el-table-column label="面值" align="center">
          <template #default="{row}">{{row.amount}}元</template>
        </el-table-column>
        <el-table-column label="适用平台" align="center">
          <template #default="{row}">{{formatPlatform(row.platform)}}</template>
        </el-table-column>
        <el-table-column label="有效期" align="center">
          <template #default="{row}">{{formatDate(row.startTime)}}至{{formatDate(row.endTime)}}</template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="{row}">{{formatStatus(row.endTime)}}</template>
        </el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template #default="{row}">
            <el-button type="success" icon="setting" @click="handleView(row)">查看</el-button>
            <el-button type="primary" icon="edit" @click="handleUpdate(row)">编辑</el-button>
            <el-popconfirm
                width="220"
                placement="bottom"
                :icon="InfoFilled"
                icon-color="#f90"
                confirm-button-text="确定"
                cancel-button-text="取消"
                title="是否确定删除？"
                @confirm="() =>handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-bar">
      <el-pagination
          background
          layout="total, sizes,prev, pager, next,jumper"
          :total="total"
          :page-sizes="[5,10,15,20]"
          v-model:page-size="listQuery.pageSize"
          v-model:current-page="listQuery.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<style scoped lang="scss">
.spikes-list {

  margin-top: 20px;
  display: flex;
  flex-direction: column;

  .spikes-search {
    //height: 100px;
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;

    .logo {
      width: 100%;
      font-size: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        margin: 0 8px;
      }

      .search-btn {
        margin-left: 30px;
        padding: 0 10px;
      }
    }

    .search {
      width: 100%;

      .el-form {
        margin-top: 20px;

        .el-form-item {
          width: 280px;
        }
      }
    }
  }

  .add-list {
    //height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;

    .add-btn {
      display: flex;
      align-items: center;

      span {
        margin-left: 8px;
        font-size: 18px;
      }
    }
  }

  .page-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;

  }
}
</style>
